<?php
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Logic;

use AuctionCore\CarResource\CarModel;
use AuctionCore\Common\PhpRedis;

class QuestionLogic extends BaseLogic
{
    protected $autoCheckFields = false;

    protected $questionModel;

    protected $questionOrderModel;

    protected $questionImagesLogic;

    protected $questionAnswerLogic;

    protected $clcwUserLogic;

    protected $redis;

    public function _initialize()
    {
        $this->questionModel = D('Question', 'Model');

        $this->questionOrderModel = D('QuestionOrder', 'Model');

        $this->questionImagesLogic = D('QuestionImages', 'Logic');

        $this->questionAnswerLogic = D('QuestionAnswer', 'Logic');

        $this->clcwUserLogic = D('ClcwUser', 'Logic');

        $this->redis = new PhpRedis(0);
    }

    /**
     * 普通提问列表
     *
     * @param int $page
     * @param int $size
     * @param     $params
     *
     * @return array
     */
    public function getCommonQuestionList($page = 1, $size = 10, $params)
    {
        $map = [];
        $map['question_type'] = ['eq', 1];
        $map['status'] = ['gt', 0];
        $cm = new CarModel();
        if ($params['activity_id'] > 0) {
            $map['activity_id'] = $params['activity_id'];
        }
        if ($params['uid'] > 0) {
            $map['user_id'] = ['eq', $params['uid']];
        }
        if ($params['t_id']) {
            $map['topic_id'] = ['eq', $params['t_id']];
        }
        if ($params['q_id']) {
            $map['question_id'] = ['eq', $params['q_id']];
        }
        if ($params['q_brand']) {
            $mbrandId = $cm->get_mbrand_id_by_name(trim($params['q_brand']));
            $map['brand_id'] = ['eq', $mbrandId];
        }
        if (isset($params['q_category'])) {
            $map['question_category'] = ['eq', $params['q_category']];
        }
        if ($params['q_keywords']) {
            $map['content'] = ['LIKE', '%' . $params['q_keywords'] . '%'];
        }
        if ($params['q_uid']) {
            $map['user_id'] = ['eq', $params['q_uid']];
        }
        if ($params['q_reward']) {
            if ($params['q_reward'] == 1) {
                $map['reward_score'] = ['gt', 0];
            } else {
                $map['reward_score'] = ['elt', 0];
            }
        }
        if ($params['q_accept_status']) {
            if ($params['q_accept_status'] == 1) {
                $map['is_accept'] = ['eq', 1];
            } else {
                $map['is_accept'] = ['eq', 0];
            }
        }
        if ($params['q_status']) {
            $map['status'] = ['eq', $params['q_status']];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $sort = $params['q_sort'];
        switch ($sort) {
            case 1:
                $order = 'answer_num DESC';
                break;
            case 2:
                $order = 'pv DESC';
                break;
            case 3:
                $order = 'uv DESC';
                break;
            case 4:
                $order = 'answer_num ASC';
                break;
            case 5:
                $order = 'pv ASC';
                break;
            case 6:
                $order = 'uv ASC';
                break;
            default:
                $order = 'question_id DESC';
                break;
        }
        $cols = 'question_id,brand_id,question_category,content,user_id,reward_score,answer_num,is_accept,
                 status,report_num,is_recommend,is_top,pv,uv,create_time';
        $total = $this->questionModel->field($cols)
            ->where($map)->count();
        $list = $this->questionModel->field($cols)
            ->where($map)
            ->page($page)
            ->limit($size)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $brand = $cm->get_model_by_id($v['brand_id'], 'mbrand');
                $list[$k]['brand_name'] = $brand['name'];
                $userInfo = $this->clcwUserLogic->getClcwUserInfo($v['user_id']);
                $list[$k]['user_name'] = $userInfo['nick_name'];
                $list[$k]['accept_status'] = $v['is_accept'] == 1 ? '已采纳' : '未采纳';
                $list[$k]['top_status'] = $v['is_top'] == 1 ? '是' : '否';
                $list[$k]['question_status'] = C('QUESTION_STATUS')[$v['status']];
                $list[$k]['content'] = mb_strlen($v['content'], 'utf-8') > 32 ?
                    msubstr($v['content'], 0, 32) : $v['content'];
                $list[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 获取问题详情
     *
     * @param int $questionId
     */
    public function getCommonQuestionInfo($questionId = 0)
    {
        $condition['question_id'] = ['eq', $questionId];
        $cols = 'question_id,user_id,content,reward_score,topic_id,is_accept,is_recommend,status,create_time';
        $res = $this->questionModel->field($cols)->where($condition)->find();
        $userInfo = $this->clcwUserLogic->getClcwUserInfo($res['user_id']);
        if ($res['topic_id'] > 0) {
            $topicInfo = D('Topic', 'Logic')->getTopicById($res['topic_id']);
            $res['topic_name'] = $topicInfo['topic_name'];
        }
        $res['user_name'] = empty($userInfo['nick_name']) ? $userInfo['mobile'] : $userInfo['nick_name'];
        $res['user_avatar'] = getFullUrl($userInfo['avatar']);
        $res['create_time'] = date("Y-m-d H:i:s", $res['create_time']);
        $res['images'] = $this->questionImagesLogic->getQuestionImagesList($questionId);
        $res['accept_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept' => 1,
                'status'    => 1
            ]
        );
        $res['recommend_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_recommend' => 1,
                'status'       => 1
            ]
        );
        $res['normal_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept'    => 0,
                'is_recommend' => 0,
                'status'       => 1
            ]
        );
        $res['disable_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'status' => [
                    '0' => 'NOT IN',
                    '1' => '1,2'
                ]
            ]
        );
        $res['recommend_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_recommend' => 1,
                'status'       => 1
            ]
        );
        return $res;
    }

    /**
     * 更新提问
     *
     * @param array $data
     * @param  int  $type 1、禁用问题 2、启用问题
     * @param int   $emp_id
     */
    public function updateQuestionStatus($data = [], $type = 1, $emp_id = 0)
    {
        if (empty($data) || empty($data['question_id'])) {
            return false;
        }
        $questionInfo = $this->getQuestion($data['question_id']);
        $questionOrderInfo = $this->questionOrderModel->where(['question_id' => $questionInfo['question_id']])->find();
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret1 = $ret2 = $ret21 = $ret22 = true;
        if ($type == 1) {
            //禁用问题减少用户提问数量
            $ret1 = $this->clcwUserLogic->decUserQuestionNum($questionInfo['user_id']);
            //1、普通问题 2、付费问题
            $userStatisticsLogic = new UserStatisticsLogic();
            if ($questionInfo['question_type'] == 1) {
                $userStatisticsLogic->decUserStatisticsCommonQuestionNum($questionInfo['user_id']);
            } else {
                $userStatisticsLogic->decUserStatisticsPayQuestionNum($questionInfo['user_id']);
            }
            //已支付的付费问题用户禁用、违规禁用触发自动激活退款
            if ($questionInfo['question_type'] == 2 && $data['status'] == 4 && $questionInfo['pay_state'] == 1) {
                $data['pay_state'] = 2;
                $condition['question_id'] = $questionInfo['question_id'];
                $ret2 = $this->questionOrderModel->where($condition)->setField('status', 2);
            }
            if ($data['status'] == 4 && $questionOrderInfo['status'] = 1 && $questionInfo['reward_score'] > 0) {
                //用户禁用提问退回悬赏积分
                $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
                $ret21 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'scoreType' => 18,
                                    'score'     => (int)$questionInfo['reward_score'],
                                    'remark'    => '用户禁用问题退回悬赏积分',
                                    'userId'    => (int)$questionInfo['user_id']
                                ],
                            'bizType'    => 5
                        ]
                    )
                );
                $ret22 = $this->questionScoreOrderModel->where(['question_id' => $questionInfo['question_id']])->save(
                    [
                        'status'      => 2,
                        'return_time' => NOW_TIME,
                        'emp_id'      => $emp_id
                    ]);
            }
        } else {
            //启用问题增加用户提问数量
            $ret1 = $this->clcwUserLogic->incUserQuestionNum($questionInfo['user_id']);
        }
        //更新问题状态
        $data['update_time'] = time();
        $ret3 = $this->updateQuestion($data);
        if (!$ret1 || !$ret2 || !$ret21 || !$ret22 || !$ret3) {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }

    /**
     * 根据提问ID获得提问详情
     *
     * @param int $answer_id
     */
    public function getQuestion($questionId = 0)
    {
        if (empty($questionId)) {
            return false;
        }
        return $this->questionModel->find($questionId);
    }

    /**
     * 更新提问
     *
     * @param array $data
     *
     * @return bool
     */
    public function updateQuestion($data = [])
    {
        if (empty($data) || empty($data['question_id'])) {
            return false;
        }
        $data['update_time'] = NOW_TIME;
        return $this->questionModel->save($data);
    }


    /**
     * 更新回答
     *
     * @param array $data
     * @param  int  $type 1、禁用 2、启用
     */
    public function updateAnswer($data = [], $type = 1)
    {
        if (empty($data) || empty($data['answer_id'])) {
            return false;
        }
        $answerInfo = $this->questionAnswerLogic->getQuestionAnswer($data['answer_id']);
        $questionInfo = $this->getQuestion($answerInfo['question_id']);
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        //更新回答状态
        $data['update_time'] = time();
        //禁用回答减少用户回答数及问题的回答数
        $ret3 = $ret4 = $ret41 = $ret42 = $ret43 = $ret51 = $ret52 = $ret53 = true;
        $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
        if ($type == 1) {
            $ret1 = $this->clcwUserLogic->dec_user_answer_num($answerInfo['user_id']);
            $ret2 = $this->decQuestionAnswerNum($answerInfo['question_id']);
            if ($answerInfo['is_accept'] == 1) { //已采纳的回答被禁用
                //付费提问采纳回答被禁用 从牛人帐号扣钱
                if ($questionInfo['question_type'] == 2) {
                    $this->redis->lpush($keyName, json_encode(
                            [
                                'bizContent' =>
                                    [
                                        'moneyType' => 42,
                                        'money'     => (float)$questionInfo['reward_price'],
                                        'remark'    => '',
                                        'userId'    => (int)$answerInfo['user_id']
                                    ],
                                'bizType'    => 7
                            ]
                        )
                    );
                }
                //禁用回答扣除积分
                $ret41 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'scoreType' => 54,
                                    'score'     => 0,
                                    'remark'    => '',
                                    'userId'    => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 5
                        ]
                    )
                );
                //禁用回答扣除经验值
                $ret51 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'expType' => 54,
                                    'exp'     => 0,
                                    'remark'  => '',
                                    'userId'  => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 6
                        ]
                    )
                );
                //禁用采纳回答扣除积分
                $ret42 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'scoreType' => 55,
                                    'score'     => 0,
                                    'remark'    => '',
                                    'userId'    => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 5
                        ]
                    )
                );
                //禁用采纳回答扣除成长值
                $ret52 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'expType' => 55,
                                    'exp'     => 0,
                                    'remark'  => '',
                                    'userId'  => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 6
                        ]
                    )
                );
                //禁用采纳回答扣除悬赏积分
                if ($questionInfo['reward_score'] > 0) {
                    $ret43 = $this->redis->lpush($keyName, json_encode(
                            [
                                'bizContent' =>
                                    [
                                        'scoreType' => 57,
                                        'score'     => (int)$questionInfo['reward_score'],
                                        'remark'    => '',
                                        'userId'    => (int)$answerInfo['user_id']
                                    ],
                                'bizType'    => 5
                            ]
                        )
                    );
                }
                //禁用采纳回答扣除悬赏经验值
                $ret53 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'expType' => 57,
                                    'exp'     => 0,
                                    'remark'  => '',
                                    'userId'  => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 6
                        ]
                    )
                );
                $ret3 = $this->clcwUserLogic->decUserAcceptNum($answerInfo['user_id']);
                $data['is_accept'] = 0;
                $ret4 = $this->questionModel->where(['question_id' => $answerInfo['question_id']])
                    ->setField('is_accept', 0);
            } else {
                $ret41 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'scoreType' => 54,
                                    'score'     => 0,
                                    'remark'    => '',
                                    'userId'    => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 5
                        ]
                    )
                );
                $ret51 = $this->redis->lpush($keyName, json_encode(
                        [
                            'bizContent' =>
                                [
                                    'expType' => 54,
                                    'exp'     => 0,
                                    'remark'  => '',
                                    'userId'  => (int)$answerInfo['user_id']
                                ],
                            'bizType'    => 6
                        ]
                    )
                );
            }
        } else {
            //启用回答增加用户回答数及问题的回答数
            $ret1 = $this->clcwUserLogic->incUserAnswerNum($answerInfo['user_id']);
            $ret2 = $this->incQuestionAnswerNum($answerInfo['question_id']);
            //启用回答添加积分
            $ret41 = $this->redis->lpush($keyName, json_encode(
                    [
                        'bizContent' =>
                            [
                                'scoreType' => 13,
                                'score'     => 0,
                                'remark'    => '',
                                'userId'    => (int)$answerInfo['user_id']
                            ],
                        'bizType'    => 5
                    ]
                )
            );
            //启用回答添加成长值
            $ret51 = $this->redis->lpush($keyName, json_encode(
                    [
                        'bizContent' =>
                            [
                                'expType' => 13,
                                'exp'     => 0,
                                'remark'  => '',
                                'userId'  => (int)$answerInfo['user_id']
                            ],
                        'bizType'    => 6
                    ]
                )
            );
        }
        $ret5 = $this->questionAnswerLogic->updateQuestionAnswer($data);
        if (!$ret1 || !$ret2 || !$ret3 || !$ret4 ||
            !$ret41 || !$ret42 || !$ret43 ||
            !$ret51 || !$ret52 || !$ret53 ||
            !$ret5
        ) {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }

    /**
     * 增加问题回答数
     *
     * @param $questionId
     */
    public function incQuestionAnswerNum($questionId = 0)
    {
        if (empty($questionId)) {
            return false;
        }
        $condition['question_id'] = $questionId;
        return $this->questionModel->where($condition)->setInc('answer_num');
    }

    /**
     * 减少问题回答数
     *
     * @param $questionId
     */
    public function decQuestionAnswerNum($questionId = 0)
    {
        if (empty($questionId)) {
            return false;
        }
        $condition['question_id'] = $questionId;
        return $this->questionModel->where($condition)->setDec('answer_num');
    }


    /**
     * 退回提问悬赏积分
     *
     * @param array $data
     * @param array $user
     */
    public function returnQuestionRewardScore($data = [], $user = [])
    {
        if (empty($data) || empty($data['question_id'])) {
            return false;
        }
        //更新提问信息
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret1 = $this->questionModel->save($data);
//        $ret2 = $uc->change_user_score($user['user_id'], 52, '退回提问悬赏积分');
        $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
        $ret2 = $this->redis->lpush($keyName, json_encode(
                [
                    'bizContent' =>
                        [
                            'scoreType' => 52,
                            'score'     => 0,
//                            'remark' => '退回提问悬赏积分',
                            'remark'    => '',
                            'userId'    => (int)$user['user_id']
                        ],
                    'bizType'    => 5
                ]
            )
        );
        if (!$ret1 || !$ret2) {
            M('', '', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }


    /**
     * 审核通过问题
     *
     * @param unknown $questionID
     */
    public function passQuestion($questionID)
    {
        $time = time();

        $id = join(',', $questionID);

        $res = $this->questionModel->where("question_id in ({$id})")->save(
            ['status'      => 1,
             'update_time' => $time
            ]
        );

        if (count($questionID) != $res) {
            return false;
        }

        return true;
    }


    /**
     * 禁用违规问题
     *
     * @param array $illegalQuestionID
     */
    public function delIllegaQuestion($illegalQuestionID)
    {

        $ids = join(',', $illegalQuestionID);

        $res = $this->questionModel
            ->where("question_id IN ({$ids})")
            ->save(
                [
                    'status'      => 3,
                    'update_time' => NOW_TIME
                ]
            );
        if (count($illegalQuestionID) != $res) {
            return false;
        }
        foreach ($illegalQuestionID as $v) {
            $question = $this->questionModel->field('reward_score,question_id,user_id')
                ->where(['question_id' => $v])
                ->find();
            if (!$question) {
                return false;
            }
            //图片审核违规禁用提问,发送消息
            $questionContent = mb_substr($question['content'], 0, 10, 'utf-8');
            $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
            $this->redis->lpush($keyName, json_encode(
                    [
                        'bizContent' =>
                            [
                                'userId'     => (string)$question['user_id'],
                                'msgTitle'   => '我的提问违规禁用',
                                'msgContent' => '【我的提问】您的提问“' . $questionContent . '”审核不通过。',
                                'msgParam'   => '',
                            ],
                        'bizType'    => 11
                    ]
                )
            );
        }
        return true;
    }

    /**
     * 问题违规减掉用户问题数
     */
    public static function decUserQuestionNum($userID)
    {
        $model = M('user', 'clcw_', 'DB_CLCW');

        $user = ['question_num' => ['exp', 'question_num-1'], 'update_time' => NOW_TIME];

        return $model->where(['user_id' => $userID])->save($user);
    }


    /**
     * 付费提问列表
     *
     * @param int $page
     * @param int $size
     * @param     $params
     *
     * @return array
     */
    public function getPayQuestionList($page = 1, $size = 10, $params)
    {
        $map = [];
        $map['question_type'] = ['eq', 2];
        $map['status'] = ['gt', 0];
        $map['pay_state'] = ['gt', 0];
        $cm = new CarModel();
        if ($params['uid'] > 0) {
            $map['user_id'] = ['eq', $params['uid']];
        }
        if ($params['t_id']) {
            $map['topic_id'] = ['eq', $params['t_id']];
        }
        if ($params['q_id']) {
            $map['question_id'] = ['eq', $params['q_id']];
        }
        if ($params['q_brand']) {
            $mbrandId = $cm->get_mbrand_id_by_name(trim($params['q_brand']));
            $map['brand_id'] = ['eq', $mbrandId];
        }
        if (isset($params['q_category'])) {
            $map['question_category'] = ['eq', $params['q_category']];
        }
        if ($params['q_keywords']) {
            $map['content'] = ['LIKE', '%' . $params['q_keywords'] . '%'];
        }
        if ($params['q_uid']) {
            $map['user_id'] = ['eq', $params['q_uid']];
        }
        if ($params['q_user_name']) {
            $user_id = $this->clcwUserLogic->getUserIdByNickName($params['q_user_name']);
            $map['user_id'] = ['eq', $user_id];
        }
        if ($params['q_answer_uid']) {
            $map['expert_id'] = ['eq', $params['q_answer_uid']];
        }
        if ($params['q_answer_username']) {
            $user_id = $this->clcwUserLogic->getUserIdByNickName($params['q_answer_username']);
            $map['expert_id'] = ['eq', $user_id];
        }
        if ($params['q_accept_status']) {
            if ($params['q_accept_status'] == 1) {
                $map['is_accept'] = ['eq', 1];
            } else {
                $map['is_accept'] = ['eq', 0];
            }
        }
        if ($params['q_status']) {
            $map['status'] = ['eq', $params['q_status']];
        }
        if ($params['is_report']) {
            $map['report_num'] = ['gt', 0];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $sort = $params['q_sort'];
        switch ($sort) {
            case 1:
                $order = 'answer_num DESC';
                break;
            case 2:
                $order = 'pv DESC';
                break;
            case 3:
                $order = 'uv DESC';
                break;
            case 4:
                $order = 'answer_num ASC';
                break;
            case 5:
                $order = 'pv ASC';
                break;
            case 6:
                $order = 'uv ASC';
                break;
            default:
                $order = 'question_id DESC';
                break;
        }
        $cols = 'question_id,brand_id,question_category,content,user_id,expert_id,reward_price,answer_num,is_accept,status,
                 report_num,is_recommend,is_top,pay_state,pv,uv,create_time';
        $total = $this->questionModel->field($cols)
            ->where($map)->count();
        $list = $this->questionModel->field($cols)
            ->where($map)
            ->page($page)
            ->limit($size)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $brand = $cm->get_model_by_id($v['brand_id'], 'mbrand');
                $list[$k]['brand_name'] = $brand['name'];
                $userInfo = $this->clcwUserLogic->getClcwUserInfo($v['user_id']);
                $list[$k]['user_name'] = $userInfo['nick_name'];
                $expertInfo = $this->clcwUserLogic->getClcwUserInfo($v['expert_id']);
                $list[$k]['expert_name'] = $expertInfo['nick_name'];
                $list[$k]['accept_status'] = $v['is_accept'] == 1 ? '已采纳' : '未采纳';
                $list[$k]['top_status'] = $v['is_top'] == 1 ? '是' : '否';
                $list[$k]['question_status'] = C('QUESTION_STATUS')[$v['status']];
                $list[$k]['content'] = mb_strlen($v['content'], 'utf-8') > 32 ?
                    msubstr($v['content'], 0, 32) : $v['content'];
                $list[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 获取付费问题详情
     *
     * @param int $questionId
     */
    public function getPayQuestionInfo($questionId = 0)
    {
        $condition['question_id'] = ['eq', $questionId];
        $cols = 'question_id,user_id,expert_id,content,reward_score,topic_id,is_accept,is_recommend,status,create_time';
        $res = $this->questionModel->field($cols)->where($condition)->find();
        $userInfo = $this->clcwUserLogic->getClcwUserInfo($res['user_id']);
        if ($res['topic_id'] > 0) {
            $topicInfo = D('Topic', 'Logic')->getTopicById($res['topic_id']);
            $res['topic_name'] = $topicInfo['topic_name'];
        }
        $res['user_name'] = empty($userInfo['nick_name']) ? $userInfo['mobile'] : $userInfo['nick_name'];
        $res['user_avatar'] = getFullUrl($userInfo['avatar']);
        $res['create_time'] = date("Y-m-d H:i:s", $res['create_time']);
        $res['images'] = $this->questionImagesLogic->getQuestionImagesList($questionId);
        $res['accept_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept' => 1,
                'status'    => 1
            ]
        );
        $res['expert_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept' => 0,
                'user_id'   => $res['expert_id'],
                'status'    => 1
            ]
        );
        $res['disable_expert_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'user_id' => $res['expert_id'],
                [
                    'status' => [
                        '0' => 'NOT IN',
                        '1' => '1,2'
                    ]
                ]
            ]
        );

        $res['normal_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'user_id' => [
                    '0' => 'NEQ',
                    '1' => $res['expert_id']
                ],
                'status'  => 1
            ]
        );
        $res['disable_normal_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'user_id' => ['0' => 'NEQ', '1' => $res['expert_id']],
                'status'  => ['0' => 'NOT IN', '1' => '1,2']
            ]
        );
        return $res;
    }

    /**
     * 激活退款
     *
     * @param int $questionId
     */
    public function activateRefund($questionId = 0)
    {
        if (empty($questionId)) {
            return false;
        }
        $condition['question_id'] = $questionId;
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret1 = $this->questionModel->where($condition)->setField('pay_state', 2);
        $ret2 = $this->questionOrderModel->where($condition)->setField('status', 2);
        if (!$ret1 || !$ret2) {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }


    /**
     * 提问举报列表
     *
     * @param int $page
     * @param int $size
     * @param     $params
     *
     * @return array
     */
    public function getReportQuestionList($page = 1, $size = 10, $params)
    {
        $map = [];
        $map['report_num'] = ['gt', 0];
        $cm = new CarModel();
        if ($params['q_id']) {
            $map['question_id'] = ['eq', $params['q_id']];
        }
        if ($params['q_brand']) {
            $mbrandId = $cm->get_mbrand_id_by_name(trim($params['q_brand']));
            $map['brand_id'] = ['eq', $mbrandId];
        }
        if ($params['q_keywords']) {
            $map['content'] = ['LIKE', '%' . $params['q_keywords'] . '%'];
        }
        if ($params['q_uid']) {
            $map['user_id'] = ['eq', $params['q_uid']];
        }
        if ($params['q_status']) {
            $map['status'] = ['eq', $params['q_status']];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = 'question_id,brand_id,content,user_id,reward_score,answer_num,is_accept,status,
                 report_num,is_recommend,is_top,create_time';
        $order = 'question_id DESC';
        $total = $this->questionModel->field($cols)
            ->where($map)->count();
        $list = $this->questionModel->field($cols)
            ->where($map)
            ->page($page)
            ->limit($size)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $brand = $cm->get_model_by_id($v['brand_id'], 'mbrand');
                $list[$k]['brand_name'] = $brand['name'];
                $userInfo = $this->clcwUserLogic->getClcwUserInfo($v['user_id']);
                $list[$k]['user_name'] = $userInfo['nick_name'];
                $list[$k]['question_status'] = C('QUESTION_STATUS')[$v['status']];
                $list[$k]['content'] = mb_strlen($v['content'], 'utf-8') > 32 ?
                    msubstr($v['content'], 0, 32) : $v['content'];
                $list[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }


    /**
     * 获取举报问题详情
     *
     * @param int $questionId
     */
    public function getReportQuestionInfo($questionId = 0)
    {
        $condition['question_id'] = ['eq', $questionId];
        $cols = 'question_id,question_type,user_id,expert_id,content,reward_score,
                 is_accept,is_recommend,status,create_time';
        $res = $this->questionModel->field($cols)->where($condition)->find();
        $userInfo = $this->clcwUserLogic->getClcwUserInfo($res['user_id']);
        $res['user_name'] = empty($userInfo['nick_name']) ? $userInfo['mobile'] : $userInfo['nick_name'];
        $res['user_avatar'] = getFullUrl($userInfo['avatar']);
        $res['create_time'] = date("Y-m-d H:i:s", $res['create_time']);
        $res['images'] = $this->questionImagesLogic->getQuestionImagesList($questionId);
        $res['accept_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept' => 1,
                'status'    => 1
            ]
        );
        $res['expert_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'user_id' => $res['expert_id'],
                'status'  => 1
            ]
        );
        $res['recommend_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_recommend' => 1,
                'status'       => 1
            ]
        );
        $res['normal_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_accept'    => 0,
                'is_recommend' => 0,
                'status'       => 1
            ]
        );
        $res['disable_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'status' => [
                    '0' => 'NOT IN',
                    '1' => '1,2'
                ]
            ]
        );
        $res['recommend_answer'] = $this->questionAnswerLogic->getQuestionAnswerList($questionId, [
                'is_recommend' => 1,
                'status'       => 1
            ]
        );
        return $res;
    }

    public function getTopicNum($topicId)
    {
        if ($topicId < 1) {
            return 0;
        }
        $condition = [];
        $condition['topic_id'] = $topicId;
        return $this->questionModel->where($condition)->count();
    }

    /**
     * 获取问题类型列表
     */
    public function getQuestionCategoryList($status = false)
    {
        $where = [];
        if ($status) {
            $where['status'] = 1;
        }
        return D('QuestionCategory', 'Model')->where($where)->select();
    }

    /**
     * 获取提问类型
     */
    public function getQuestionCategory($id)
    {
        if (empty($id)) {
            return false;
        }
        return D('QuestionCategory', 'Model')->where(['id' => $id])->find();
    }

    /**
     * 保存提问类型
     */
    public function saveQuestionCategory($data)
    {
        $id = $data['id'];
        unset($data['id']);
        if (empty($data['category_name'])) {
            unset($data['category_name']);
        }

        if (!empty($id)) {
            $data['update_time'] = NOW_TIME;
            $res = D('QuestionCategory', 'Model')->where(['id' => $id])->save($data);
        } else {
            $data['create_time'] = NOW_TIME;
            $res = D('QuestionCategory', 'Model')->add($data);
        }
        return $res;
    }

    /**
     * 获取活动问答数量
     *
     * @param int $activityId
     */
    public function getActivityQuestionNum($activityId = 0)
    {
        if (empty($activityId)) {
            return false;
        }
        $condition['activity_id'] = $activityId;
        $condition['question_type'] = 1;
        $condition['status'] = ['gt', 0];
        return $this->questionModel->where($condition)->count();
    }
}